home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C18 / Effector.txt < prev    next >
Encoding:
Text File  |  2000-05-25  |  1.4 KB  |  57 lines

  1. //: C18:Effector.txt
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // (Should be "cpp" but I can't get it to compile with
  7. // My windows compilers, so making it a txt file will
  8. // keep it out of the makefile for the time being)
  9. // Jerry Schwarz's "effectors"
  10. #include<iostream>
  11. #include <cstdlib>
  12. #include <string>
  13. #include <climits> // ULONG_MAX
  14. using namespace std;
  15.  
  16. // Put out a portion of a string:
  17. class Fixw {
  18.   string str;
  19. public:
  20.   Fixw(const string& s, int width)
  21.     : str(s, 0, width) {}
  22.   friend ostream& 
  23.   operator<<(ostream& os, Fixw& fw) {
  24.     return os << fw.str;
  25.   }
  26. };
  27.  
  28. typedef unsigned long ulong;
  29.  
  30. // Print a number in binary:
  31. class Bin {
  32.   ulong n;
  33. public:
  34.   Bin(ulong nn) { n = nn; }
  35.   friend ostream& operator<<(ostream&, Bin&);
  36. };
  37.  
  38. ostream& operator<<(ostream& os, Bin& b) {
  39.   ulong bit = ~(ULONG_MAX >> 1); // Top bit set
  40.   while(bit) {
  41.     os << (b.n & bit ? '1' : '0');
  42.     bit >>= 1;
  43.   }
  44.   return os;
  45. }
  46.  
  47. int main() {
  48.   char* string =
  49.     "Things that make us happy, make us wise";
  50.   for(int i = 1; i <= strlen(string); i++)
  51.     cout << Fixw(string, i) << endl;
  52.   ulong x = 0xCAFEBABEUL;
  53.   ulong y = 0x76543210UL;
  54.   cout << "x in binary: " << Bin(x) << endl;
  55.   cout << "y in binary: " << Bin(y) << endl;
  56. } ///:~
  57.